package com.aspire.aimini.controller;

import com.aspire.aimini.model.dto.MaterialDTO;
import com.aspire.aimini.model.query.MaterialQuery;
import com.aspire.aimini.service.MaterialService;
import com.aspire.aimini.util.JwtUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.util.List;
import java.util.Map;

/**
 * 素材管理Controller
 *
 * @author wangguiyou
 * @date 2024-01-01
 * @description 素材管理相关接口
 */
@Slf4j
@RestController
@RequestMapping("/api/materials")
@RequiredArgsConstructor
@Tag(name = "素材管理", description = "素材上传、查询、管理等功能")
public class MaterialController {

    private final MaterialService materialService;
    private final JwtUtil jwtUtil;

    @PostMapping("/upload")
    @Operation(summary = "上传素材", description = "支持多文件上传，返回上传成功的素材列表")
    public ApiResponse<List<MaterialDTO>> uploadMaterials(
            @Parameter(description = "上传的文件列表") @RequestParam("files") List<MultipartFile> files,
            @Parameter(description = "素材描述") @RequestParam(value = "description", required = false) String description,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        List<MaterialDTO> result = materialService.uploadMaterials(files, description, userId);
        return ApiResponse.success(result);
    }

    @GetMapping
    @Operation(summary = "获取素材列表", description = "分页查询素材列表，支持多种筛选条件")
    public ApiResponse<IPage<MaterialDTO>> getMaterialPage(
            @Parameter(description = "页码") @RequestParam(value = "page", defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(value = "size", defaultValue = "20") Integer size,
            @Parameter(description = "搜索关键词") @RequestParam(value = "keyword", required = false) String keyword,
            @Parameter(description = "标签ID列表") @RequestParam(value = "tags", required = false) List<Long> tags,
            @Parameter(description = "来源类型") @RequestParam(value = "sourceType", required = false) String sourceType,
            @Parameter(description = "文件类型") @RequestParam(value = "fileType", required = false) String fileType,
            @Parameter(description = "是否收藏") @RequestParam(value = "isFavorite", required = false) Boolean isFavorite,
            @Parameter(description = "是否归档") @RequestParam(value = "isArchived", required = false) Boolean isArchived,
            @Parameter(description = "排序字段") @RequestParam(value = "sortBy", defaultValue = "createTime") String sortBy,
            @Parameter(description = "排序方向") @RequestParam(value = "sortOrder", defaultValue = "desc") String sortOrder,
            @Parameter(description = "开始时间") @RequestParam(value = "startTime", required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(value = "endTime", required = false) String endTime,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);

        MaterialQuery query = new MaterialQuery();
        query.setUserId(userId);
        query.setPage(page);
        query.setSize(size);
        query.setKeyword(keyword);
        query.setTags(tags);
        query.setSourceType(sourceType);
        query.setFileType(fileType);
        query.setIsFavorite(isFavorite);
        query.setIsArchived(isArchived);
        query.setSortBy(sortBy);
        query.setSortOrder(sortOrder);
        query.setStartTime(startTime);
        query.setEndTime(endTime);

        IPage<MaterialDTO> result = materialService.getMaterialPage(query);
        return ApiResponse.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取素材详情", description = "根据素材ID获取详细信息")
    public ApiResponse<MaterialDTO> getMaterialById(
            @Parameter(description = "素材ID") @PathVariable Long id,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        MaterialDTO result = materialService.getMaterialById(id, userId);
        return ApiResponse.success(result);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新素材信息", description = "更新素材的描述、收藏状态、归档状态等")
    public ApiResponse<MaterialDTO> updateMaterial(
            @Parameter(description = "素材ID") @PathVariable Long id,
            @Parameter(description = "素材描述") @RequestParam(value = "description", required = false) String description,
            @Parameter(description = "是否收藏") @RequestParam(value = "isFavorite", required = false) Boolean isFavorite,
            @Parameter(description = "是否归档") @RequestParam(value = "isArchived", required = false) Boolean isArchived,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        MaterialDTO result = materialService.updateMaterial(id, description, isFavorite, isArchived, userId);
        return ApiResponse.success(result);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除素材", description = "根据素材ID删除素材")
    public ApiResponse<Void> deleteMaterial(
            @Parameter(description = "素材ID") @PathVariable Long id,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        materialService.deleteMaterial(id, userId);
        return ApiResponse.success();
    }

    @DeleteMapping("/batch")
    @Operation(summary = "批量删除素材", description = "根据素材ID列表批量删除素材")
    public ApiResponse<Void> batchDeleteMaterials(
            @Parameter(description = "素材ID列表") @RequestBody List<Long> ids,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        materialService.batchDeleteMaterials(ids, userId);
        return ApiResponse.success();
    }

    @PostMapping("/{id}/tags")
    @Operation(summary = "为素材添加标签", description = "为指定素材添加标签")
    public ApiResponse<Void> addTagsToMaterial(
            @Parameter(description = "素材ID") @PathVariable Long id,
            @Parameter(description = "标签ID列表") @RequestBody List<Long> tagIds,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        materialService.addTagsToMaterial(id, tagIds, userId);
        return ApiResponse.success();
    }

    @DeleteMapping("/{id}/tags")
    @Operation(summary = "从素材移除标签", description = "从指定素材移除标签")
    public ApiResponse<Void> removeTagsFromMaterial(
            @Parameter(description = "素材ID") @PathVariable Long id,
            @Parameter(description = "标签ID列表") @RequestBody List<Long> tagIds,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        materialService.removeTagsFromMaterial(id, tagIds, userId);
        return ApiResponse.success();
    }

    @PostMapping("/{id}/view")
    @Operation(summary = "增加查看次数", description = "增加素材的查看次数")
    public ApiResponse<Void> incrementViewCount(
            @Parameter(description = "素材ID") @PathVariable Long id,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        materialService.incrementViewCount(id, userId);
        return ApiResponse.success();
    }

    @PostMapping("/{id}/download")
    @Operation(summary = "获取下载链接", description = "获取素材的下载链接并增加下载次数")
    public ApiResponse<String> getDownloadUrl(
            @Parameter(description = "素材ID") @PathVariable Long id,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        String downloadUrl = materialService.getDownloadUrl(id, userId);
        return ApiResponse.success(downloadUrl);
    }

    @GetMapping("/favorites")
    @Operation(summary = "获取收藏素材", description = "获取用户收藏的素材列表")
    public ApiResponse<IPage<MaterialDTO>> getFavoriteMaterials(
            @Parameter(description = "页码") @RequestParam(value = "page", defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(value = "size", defaultValue = "20") Integer size,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        IPage<MaterialDTO> result = materialService.getFavoriteMaterials(userId, page, size);
        return ApiResponse.success(result);
    }

    @GetMapping("/recent")
    @Operation(summary = "获取最近素材", description = "获取最近上传的素材列表")
    public ApiResponse<List<MaterialDTO>> getRecentMaterials(
            @Parameter(description = "限制数量") @RequestParam(value = "limit", defaultValue = "10") Integer limit,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        List<MaterialDTO> result = materialService.getRecentMaterials(userId, limit);
        return ApiResponse.success(result);
    }

    @GetMapping("/by-tags")
    @Operation(summary = "根据标签查询素材", description = "根据标签ID列表查询相关素材")
    public ApiResponse<IPage<MaterialDTO>> getMaterialsByTags(
            @Parameter(description = "标签ID列表") @RequestParam("tagIds") List<Long> tagIds,
            @Parameter(description = "页码") @RequestParam(value = "page", defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(value = "size", defaultValue = "20") Integer size,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        IPage<MaterialDTO> result = materialService.getMaterialsByTags(tagIds, userId, page, size);
        return ApiResponse.success(result);
    }

    @GetMapping("/{id}/similar")
    @Operation(summary = "查找相似素材", description = "根据素材ID查找相似的素材")
    public ApiResponse<List<MaterialDTO>> findSimilarMaterials(
            @Parameter(description = "素材ID") @PathVariable Long id,
            @Parameter(description = "限制数量") @RequestParam(value = "limit", defaultValue = "10") Integer limit,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        List<MaterialDTO> result = materialService.findSimilarMaterials(id, userId, limit);
        return ApiResponse.success(result);
    }

    @GetMapping("/stats")
    @Operation(summary = "获取素材统计", description = "获取用户的素材统计信息")
    public ApiResponse<Map<String, Object>> getUserMaterialStats(HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        Map<String, Object> result = materialService.getUserMaterialStats(userId);
        return ApiResponse.success(result);
    }

    @GetMapping("/stats/file-type")
    @Operation(summary = "按文件类型统计", description = "按文件类型统计素材数量")
    public ApiResponse<List<Map<String, Object>>> countByFileType(HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        List<Map<String, Object>> result = materialService.countByFileType(userId);
        return ApiResponse.success(result);
    }

    @GetMapping("/stats/source-type")
    @Operation(summary = "按来源类型统计", description = "按来源类型统计素材数量")
    public ApiResponse<List<Map<String, Object>>> countBySourceType(HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        List<Map<String, Object>> result = materialService.countBySourceType(userId);
        return ApiResponse.success(result);
    }

    @PostMapping("/{id}/thumbnail")
    @Operation(summary = "生成缩略图", description = "为指定素材生成缩略图")
    public ApiResponse<String> generateThumbnail(
            @Parameter(description = "素材ID") @PathVariable Long id,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        String thumbnailPath = materialService.generateThumbnail(id, userId);
        return ApiResponse.success(thumbnailPath);
    }

    @PostMapping("/thumbnails/batch")
    @Operation(summary = "批量生成缩略图", description = "为指定素材列表批量生成缩略图")
    public ApiResponse<Integer> batchGenerateThumbnails(
            @Parameter(description = "素材ID列表") @RequestBody List<Long> materialIds,
            HttpServletRequest request) {
        Long userId = jwtUtil.getUserIdFromRequest(request);
        int successCount = materialService.batchGenerateThumbnails(materialIds, userId);
        return ApiResponse.success(successCount);
    }
}